package com.zjdiepu.www.manage.api.yw;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.BusiStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.DataDicType;
import com.zjdiepu.www.base.enums.type.ModeIDType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.lang.ZNode;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.commpent.mapper.base.OtherAttachmentsVoMapper;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessVoMapper;
import com.zjdiepu.www.ibiz.base.IDpBaseContractVersionService;
import com.zjdiepu.www.ibiz.base.IOtherAttachmentsService;
import com.zjdiepu.www.ibiz.cache.ICachedDictionaryService;
import com.zjdiepu.www.ibiz.file.IQiniuFileService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessService;
import com.zjdiepu.www.ibiz.yw.IYwContractsRegisterService;
import com.zjdiepu.www.model.base.dto.DpBaseContractVersion;
import com.zjdiepu.www.model.base.dto.SimpleDataDictionary;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.base.ext.DpBaseContractVersionExt;
import com.zjdiepu.www.model.base.ext.OtherAttachmentsExt;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.dto.YwContractsRegister;
import com.zjdiepu.www.model.yw.ext.YwContractsRegisterExt;
import com.zjdiepu.www.model.yw.request.YwBusinessQueryRequest;

/**
 * 合同登记Controller层<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年05月04日 17时08分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "YwContractsRegisterController", produces="application/json;charset=UTF-8")
@Api(tags = {"合同登记"}, produces="application/json;charset=UTF-8")
public class YwContractsRegisterController extends BaseController {
    @Resource
    private IYwContractsRegisterService ywContractsRegisterService;
    @Resource
    private IOtherAttachmentsService otherAttachmentsService;
    @Resource
    private IYwBusinessService ywBusinessService;
    @Resource
    private YwBusinessVoMapper ywBusinessVoMapper;
    @Resource
    private IDpBaseContractVersionService dpBaseContractVersionService;
    @Resource
    private OtherAttachmentsVoMapper otherAttachmentsVoMapper;
    @Resource
    private IQiniuFileService qiniuFileService;
    @Resource
    private ICachedDictionaryService cachedDictionaryService;
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: signContractList <br/>
     * @Description: 精确定位客户签署合同 <br/>
     * @param ywBusinessExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "精确定位客户签署合同 ",response = YwBusiness.class, httpMethod="POST", tags={"签署合同"})
    @RequestMapping(value = "signContractList", method = RequestMethod.POST)
    public ApiResponse signContractList(@Validated @ModelAttribute YwBusinessQueryRequest ywBusinessQueryRequest){
    	SysUser sysUser = (SysUser)getCurrentUser();
        PageVo page = getPage(ywBusinessQueryRequest);
        ywBusinessQueryRequest.setBaseWhere();
        ywBusinessQueryRequest.setBankLoan(sysUser.getLoanBank());
        ywBusinessQueryRequest.setCodeUnits(sysUser.getCodeUnits());
        ywBusinessQueryRequest.setNeedLimit(true);
    	ywBusinessQueryRequest.setMinBusiStatus(BusiStatus.QIAN_SHU_HE_TONG_ZHONG.getCode());//"初始终审"（不包括）
    	ywBusinessQueryRequest.setMaxBusiStatus(BusiStatus.YIN_HANG_YI_FANG_KUAN.getCode());//"银行已放款"（包括）
    	int records = ywBusinessService.countLessOptionsByExt(ywBusinessQueryRequest);
    	page.setRecords(records);
    	if (records > 0) {
    		List<YwBusiness> ywBusinesss = ywBusinessService.selectLessOptionsByExt(ywBusinessQueryRequest);
    		ywBusinessVoMapper.mapper(ywBusinesss);
    		page.setRows(ywBusinesss);
    	} else {
    		page.setRows(CollectionInitUtil.emptyList());
    	}
    	return ApiResponse.success(page);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: queryContractVersion <br/>
     * @Description: 查询合同版本<br/>
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "签署合同", response = Boolean.class, httpMethod="POST", tags={"签署合同"})
    @RequestMapping(value = "queryContractVersion", method = RequestMethod.POST)
    public ApiResponse queryContractVersion() {

    	DpBaseContractVersionExt dpBaseContractVersionExt = new DpBaseContractVersionExt();
    	dpBaseContractVersionExt.withOutPage();
    	dpBaseContractVersionExt.setBaseWhere();
    	dpBaseContractVersionExt.setOrderSql("`CONTRACT_VERSION`");
    	
    	List<ZNode> znodes = new ArrayList<ZNode>();
    	
    	List<SimpleDataDictionary> simpleDataDictionarys = cachedDictionaryService.getCachedDataDics(DataDicType.BANK);
    	for(SimpleDataDictionary simpleDataDictionary : simpleDataDictionarys) {
    		String dicValue = simpleDataDictionary.getValue();
    		ZNode zNode = new ZNode(dicValue, null, simpleDataDictionary.getName(), true, true);
    		znodes.add(zNode);
    		
    		dpBaseContractVersionExt.setDataDictionaryValue(dicValue);
    		List<DpBaseContractVersion> dpBaseContractVersions = dpBaseContractVersionService.selectByExt(dpBaseContractVersionExt);
    		znodes.addAll(dpBaseContractVersions.stream().map(item -> new ZNode(item.getId(), dicValue, item.getContractVersion(), false, false)).collect(Collectors.toList()));
    	}
        return ApiResponse.success(znodes);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: contractsDetail  <br/>
     * @Description: 合同详情 <br/>
     * @param busiId
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "合同详情", response = Boolean.class, httpMethod="POST", tags={"合同详情"})
    @RequestMapping(value = "contractsDetail", method = RequestMethod.POST)
    public ApiResponse contractsDetail(String busiId) {
    	getCurrentUser();
    	if(StringUtils.isEmpty(busiId)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	YwContractsRegisterExt ywContractsRegisterExt = new YwContractsRegisterExt();
    	ywContractsRegisterExt.setBaseWhere();
    	ywContractsRegisterExt.setBusiId(busiId);
    	ywContractsRegisterExt.setRows(1);
    	List<YwContractsRegister> ywContractsRegisters = ywContractsRegisterService.selectByExt(ywContractsRegisterExt);
    	if(CollectionUtils.isNotEmpty(ywContractsRegisters)) {
    		YwContractsRegister ywContractsRegister = ywContractsRegisters.get(0);
    		return  ApiResponse.success(ywContractsRegister);
    	} else {
    		return ApiResponse.success(null);
    	}
    	
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: save  <br/>
     * @Description: 新增合同登记 <br/>
     * @param ywContractsRegister
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增合同登记", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ApiResponse save(@Validated(Add.class) @ModelAttribute YwContractsRegister ywContractsRegister) {
    	AbstractSysUser currentUser = getCurrentUser();
    	OtherAttachmentsExt otherAttachmentsExt = new OtherAttachmentsExt();
    	otherAttachmentsExt.setBaseWhere();
    	otherAttachmentsExt.withOutPage();
    	otherAttachmentsExt.setDataid(ywContractsRegister.getBusiId());// 所属业务
    	otherAttachmentsExt.setModeId(ModeIDType.QSHT.getCode()); // 所处阶段
    	int countAttachment = otherAttachmentsService.countByExt(otherAttachmentsExt);
    	if(countAttachment < 1) {
    		return ApiResponse.fail(100, "请上传签署合同附件");
    	}
    	ywContractsRegisterService.save(ywContractsRegister, currentUser);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: remove  <br/>
     * @Description: 删除合同登记<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除合同登记", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywContractsRegisterService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: disable  <br/>
     * @Description: 禁用合同登记<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "禁用合同登记", response = Boolean.class, httpMethod="POST", tags={"禁用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public ApiResponse disable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywContractsRegisterService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.INVALID.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: enable <br/>
     * @Description: 启用合同登记<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "启用合同登记", response = Boolean.class, httpMethod="POST", tags={"启用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public ApiResponse enable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywContractsRegisterService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.NORMAL.getCode(), ids);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: modify  <br/>
     * @Description: 修改合同登记 <br/>
     * @param ywContractsRegister
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改合同登记", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute YwContractsRegister ywContractsRegister) {
    	AbstractSysUser currentUser = getCurrentUser();
    	ywContractsRegister.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	ywContractsRegister.setModifierName(currentUser.getName());
    	ywContractsRegisterService.saveUpdateAndDelete(ywContractsRegister, OperateType.edit);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询合同登记<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询合同登记", response = YwContractsRegister.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       YwContractsRegister ywContractsRegister = ywContractsRegisterService.selectById(id);
       if(null == ywContractsRegister) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(ywContractsRegister);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 条件查询合同登记 <br/>
     * @param ywContractsRegisterExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询合同登记",response = YwContractsRegister.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute YwContractsRegisterExt ywContractsRegisterExt){
        ywContractsRegisterExt.notDeleted();
        PageVo page = getPage(ywContractsRegisterExt);
        int records = ywContractsRegisterService.countByExt(ywContractsRegisterExt);
        page.setRecords(records);
        if (records > 0) {
            List<YwContractsRegister> ywContractsRegisters = ywContractsRegisterService.selectByExt(ywContractsRegisterExt);
            page.setRows(ywContractsRegisters);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }

}
